#include "my_AT89S52.h"

#define DELAY_LOOP_TIMES 0X111
#define BUF_SIZE  8


const uchar LED_NUM[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07, /*0~7*/
                         0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71}; /*8~f*/


const uchar DISPLAY_BIT[] = {0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};


uchar led_scan_pointer = 0;


uchar buf[BUF_SIZE];


void delay(uchar time)
{
    unsigned int loop;
    unsigned char loop2;

    for (loop2 = 0; loop2 != time; loop2++) {
        for (loop = 0; loop != DELAY_LOOP_TIMES; loop++) {
            ;
        }
    }
}


void led_flush(void)
{
    uchar index;

    for (index = 0; index < 8; index++) {
        buf[index] = 0x00; 
    }
}



void led_print_dec(ulong num)
{
    uchar display_data_index;
    uchar index = 0;

    led_flush();

    do {
        display_data_index = num % 10;
        buf[index++] = LED_NUM[display_data_index]; 
        num /= 10;
    } while ( num != 0);
}


void led_print_hex(ulong num)
{
    uchar display_data_index;
    uchar index = 0;

    do {
        display_data_index = num % 16;
        buf[index++] = LED_NUM[display_data_index]; 
        num /= 16;
    } while ( num != 0);
}


void led_scan()
{
    P0 = buf[led_scan_pointer];
    P1 = DISPLAY_BIT[7 - led_scan_pointer];
    led_scan_pointer++;
    if (led_scan_pointer == 8) {
        led_scan_pointer = 0;
    }
}


const uchar line_scan[4] = {0xf7, 0xfb, 0xfd, 0xfe}; 


const uchar key_code[4][4] = { {  0,  1,  2,  3},
                               {  4,  5,  6,  7},
                               {  8,  9, 10, 11},
                               { 12, 13, 14, 15} };

uchar key_scan(void)
{
    uchar scan_index;
    uchar high, low, x, y;

    P2 = 0xff;
    for (scan_index = 0; scan_index != 4; scan_index++) {
        P2 = line_scan[scan_index];
        high = P2 & 0xf0;
        if (high != 0xf0) {
            switch (high) {
                case 0xe0:
                    y = 0;
                    break;
                case 0xd0:
                    y = 1;
                    break;
                case 0xb0:
                    y = 2;
                    break;
                case 0x70:
                    y = 3;
                    break;
            }
            low = P2 & 0x0f;
            switch (low) {
                case 0x0e:
                    x = 0;
                    break;
                case 0x0d:
                    x = 1;
                    break;
                case 0x0b:
                    x = 2;
                    break;
                case 0x07:
                    x = 3;
                    break;
            }
            return key_code[x][y];
        }
    }
    return 0xff;
}


uchar key_not_pressed(uchar key)
{
    if (key == 0xff)
        return(1);
    else
        return(0);
}
